<template>
  <div>
    <HeaderSelector></HeaderSelector>
    <!--展示用户信息-->

    <div class="maincontent">
      <h3>个人信息</h3>

      <el-row :gutter="20">
        <el-col :span="6">
          <!--用户头像-->
          <div class="demo-image">
            <div class="block">
              <el-image
                  style="width: 100px; height: 100px"
                  :src="url">
              </el-image>
            </div>
          </div>
        </el-col>
        <el-col :span="12">
          <i class="el-icon-user"> {{ ruleForm.username }}</i>
          <br>
          <i class="el-icon-chat-line-round"> {{ ruleForm.email }}</i>
          <br>
          <i class="el-icon-more-outline"> {{ ruleForm.description }}</i>
          <br><br>

          <!--用户更改-->
          <div>
            <el-popover
                placement="right"
                width="400"
                trigger="click">

              <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="70px" class="demo-ruleForm">
                <el-form-item label="用户名" prop="username">
                  <el-input v-model="ruleForm.username"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                  <el-input v-model="ruleForm.email"></el-input>
                </el-form-item>
                <el-form-item label="描述" prop="description">
                  <el-input v-model="ruleForm.description"></el-input>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="submitForm('ruleForm')">修改</el-button>
                </el-form-item>
              </el-form>

              <el-button slot="reference" type="primary">修改个人信息</el-button>
            </el-popover>


            &nbsp;
            <el-popover
                placement="right"
                width="200"
                trigger="click">
              <el-card v-for="blog in likeBlogs" shadow="hover" @click.native="toDetail(blog.id)" class="collecttitle">
                {{ blog.title }}
              </el-card>
              <el-button slot="reference" type="success">我的点赞</el-button>
            </el-popover>

            &nbsp;
            <el-popover
                placement="right"
                width="200"
                trigger="click">
              <el-input v-model="shareDescription" placeholder="请输入收藏夹介绍" size="small"></el-input>
              <el-button type="success" size="mini" plain @click="shareCollections">分享收藏</el-button>
              <el-button type="primary" size="mini" plain @click="noShareCollections">取消分享</el-button>
              <el-card v-for="blog in collectedBlogs" shadow="hover" @click.native="toDetail(blog.id)"
                       class="collecttitle">
                {{ blog.title }}
              </el-card>
              <el-button slot="reference" type="warning">我的收藏</el-button>
            </el-popover>


          </div>
        </el-col>
      </el-row>


      <el-row>
        <el-col :span="6">
          <!--头像上传组件-->
          <el-upload
              class="upload-demo"
              action=""
              :before-upload="BeforeUpload"
              :http-request="Upload"
              list-type="picture">

            <el-tooltip class="item" effect="light" content="只能上传jpg/png文件，且不超过2mb" placement="bottom">
              <el-button size="small" type="primary" class="changeAvatar">更改头像</el-button>
            </el-tooltip>
          </el-upload>
        </el-col>
      </el-row>

      <!--展示用户文章-->
      <br>

      <div class="myBlog">
        <h3>我的文章</h3>
        <div class="block">
          <el-timeline>

            <el-timeline-item :timestamp="blog.created" placement="top" v-for="blog in blogs">
              <el-card>
                <el-row>
                  <el-col :span="16">
                    <h4>
                      <router-link :to="{name: 'BlogDetail', params: {blogId: blog.id}}">
                        {{ blog.title }}
                      </router-link>
                    </h4>
                    <p>{{ blog.description }}</p></el-col>
                  <el-col :span="8" class="metasManage">
                    <el-button type="text" @click="dialogVisible = true,transportId(blog.id)">分类</el-button>
                  </el-col>
                </el-row>

              </el-card>
            </el-timeline-item>
          </el-timeline>

          <!--分类处理-->
          <el-dialog
              title="分类管理"
              :visible.sync="dialogVisible"
              width="30%"
              :before-close="handleClose">
            <span>目前该博客的分类是：{{ metas }}</span>
            <br>
            <br>
            <!--动态性地生成标签-->
            <el-checkbox-group v-model="metasFromFront">
              <el-checkbox
                  v-for="(item, index) in metasFromBack"
                  :key="index"
                  :label="item.label"
              >{{ item.label }}
              </el-checkbox>
            </el-checkbox-group>

            <span slot="footer" class="dialog-footer">
                    <el-button @click="delMeta" type="danger">重置(删除该博客的分类)</el-button>
                     <el-button type="primary" @click="classify">确 定</el-button>
                    </span>
          </el-dialog>


          <el-pagination class="mpage"
                         background
                         layout="prev, pager, next"
                         :current-page="currentPage"
                         :page-size="pageSize"
                         :total="total"
                         @current-change=page>
          </el-pagination>

        </div>
      </div>
    </div>
  </div>

</template>

<script>
import HeaderView from "../components/HeaderView";
import HeaderSelector from "../components/HeaderSelector";

export default {
  inject: ["reload"],
  name: "UserHome",
  // Componets: "HeaderSelectot",
  components: {HeaderSelector, HeaderView},
  data() {
    return {
      ruleForm: {
        username: '',
        email: '',
        description: '',
      },
      rules: {
        username: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
          {min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur'}
        ],
        email: [
          {required: false, type: 'email', message: '请输入正确的邮箱', trigger: 'change'}
        ]
      },

      blogs: {},
      currentPage: 1,
      total: 0,
      pageSize: 5,

      collectedBlogs: {},  //收藏文章
      likeBlogs: {}, //点过赞的文章
      url: '',

      show: false,

      //用于实现文件上传
      newFile: new FormData(),


      //分类管理
      dialogVisible: false,
      metas: [],  //用于回显该文章的分类
      blogId: '', //临时保存目前文章id  看看等会是否可以清空

      metasFromFront: [],  //前台选中发送给后端的
      metasFromBack: [],//从后台来的metas

      shareDescription: '',
    }
  },
  methods: {
    //分享收藏
    shareCollections() {
      this.$axios.post("/shareMyCollections?description=", this.shareDescription, {
        headers: {
          "Authorization": localStorage.getItem("token")
        }
      }).then(res => {
        this.$message({
          type: 'success',
          message: '分享成功，待管理员通过'
        })

      })
    },

    noShareCollections() {
      this.$axios.post("/noShareMyCollections", {
        headers: {
          "Authorization": localStorage.getItem("token")
        }
      }).then(res => {
        this.$message({
          type: 'success',
          message: '取消成功'
        })

      })
    },
    page(currentPage) {
      const _this = this

      //获取到当前登录的用户
      var userinfo = _this.$store.getters.getUser
      // var userinfo  = sessionStorage.getItem('userinfo')   //sessionStorage这里面装的是json字符串  不是对象

      //获取用户的文章
      _this.$axios.get("/blogOfUser?currentPage=" + currentPage).then(res => {
        console.log(res)
        _this.blogs = res.data.data.records
        _this.currentPage = res.data.data.current
        _this.total = res.data.data.total
        _this.pageSize = res.data.data.size

      })
    },

    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          console.log('验证过')
          this.editUser()
        }
      })
    },

    editUser() {
      const _this = this

      if (this.ruleForm != null) {
        this.$axios.post('/user/editUser', this.ruleForm, {
          headers: {
            "Authorization": localStorage.getItem("token")
          }
        }).then(res => {
          console.log(res)
          _this.$alert('操作成功', '提示', {
            confirmButtonText: '确定'
          });

          const userinfo = res.data.data //后端返回的登录用户信息（不包含密码）

          this.username = userinfo.username
          this.email = userinfo.email


          _this.$store.commit("SET_USERINFO", userinfo)

        })
      }
    },

    BeforeUpload(file) {

      const isImg = file.size / 1024 / 1024 < 2
      if (!isImg) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
        return false;
      }

      const isType = file.type === "image/png"
      const isType2 = file.type === "image/jpeg"

      if (!isType && !isType2) {
        this.$message.error('上传头像图片格式为png或jpg')
        return false
      }

      if (file) {
        this.newFile.append('file', file); //  2. 上传之前，拿到file对象，并将它添加到刚刚定义的FormData对象中。
        console.log(this.newFile.get('file'))
      } else {
        return false;
      }
    },

    Upload() {
      const newData = this.newFile;
      var _this = this
      this.$axios({
        url: '/user/avatarupload',
        method: 'post',
        data: newData,
        headers: {
          'Content-Type': 'multipart/ruleForm-data',
          "Authorization": localStorage.getItem("token")   //请求头携带的token
        }
      })
          .then(res => {
            console.log('res:', res)
            //后端更新后  前端还要刷新userinfo
            const userinfo = res.data.data //后端返回的登录用户信息（不包含密码）
            _this.$store.commit("SET_USERINFO", userinfo)

            _this.url = userinfo.avatar
            this.reload()

          })
    },

    handleClose(done) {
      this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {
          });
    }
    ,

    transportId(id) {
      this.blogId = id
      this.$axios.get("/queryBlogMetas?bid=" + id).then(res => {
        this.metas = res.data.data
      })
    }
    ,

    classify() {
      this.$axios.post("/addBlogMeta?bid=" + this.blogId, {"metas": this.metasFromFront}).then(res => {
        this.$message({
          type: "success",
          message: "分类成功",
        })

        this.metasFromFront = []
        this.dialogVisible = false
      })
    }
    ,


    delMeta() {
      this.$axios.delete("/delBlogMetaByBid?bid=" + this.blogId).then(res => {
        this.$message({
          type: 'success',
          message: '重置成功'
        })
        this.dialogVisible = false
      })
    }
    ,
    //跳转到收藏文章细节
    toDetail(bid) {
      this.$router.push({name: 'BlogDetail', params: {blogId: bid}})
    }

  },
  created() {
    this.page(1)
    var userinfo = this.$store.getters.getUser

    // this.url = 'http://localhost:8081'+userinfo.avatar
    // console.log("头像：" + userinfo.avatar)
    // console.log("地址测试" + this.$axios.defaults.baseURL)

    //拼接url
    this.url = userinfo.avatar

    this.ruleForm.username = userinfo.username
    this.ruleForm.email = userinfo.email
    this.ruleForm.description = userinfo.description

    //修改用户  自动传参用户id
    this.ruleForm.id = userinfo.id

    //生成分类标签
    this.$axios.get("/getMetas").then(res => {

      var meta = {label: ''}
      var metas = new Array();

      for (var i = 0; i < res.data.data.count; i++) {
        //牛啊牛啊
        meta = {}   //必须要清空一次  //只用下面这一句不够
        meta.label = res.data.data.labels[i]
        metas[i] = meta
      }
      this.metasFromBack = metas
    })

    //返回收藏文章
    this.$axios.post("/showMyCollection", null, {
      headers: {
        "Authorization": localStorage.getItem("token")
      }
    }).then(res => {
      this.collectedBlogs = res.data.data
    })

    //返回点赞文章
    this.$axios.post("/showMyLike", null, {
      headers: {
        "Authorization": localStorage.getItem("token")
      }
    }).then(res => {
      this.likeBlogs = res.data.data
    })
  },

}
</script>

<style scoped>
.mpage {
  margin: 0 auto;
  text-align: center;
}

.transition-box {
  margin-bottom: 10px;
  width: 200px;
  height: 100px;
  border-radius: 4px;
  text-align: center;
  color: #fff;
  padding: 40px 20px;
  box-sizing: border-box;
  margin-right: 20px;
}

.myBlog {
  width: 60%;
  margin: auto;

}

.demo-image {
  margin: auto;
  text-align: center;
}

/*头像上传*/
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.upload-demo {
  /*margin: auto;*/
  position: relative;
  right: 5px;
  text-align: center;

}

.metasManage {
  text-align: right;
}

.maincontent {
  position: relative;
  top: 20px;
}

.collecttitle {
  font-weight: bolder;
}

</style>